package io.github.lamtong.osgi.client;

import io.github.lamtong.osgi.api.HelloService;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 客户端自定义 {@link BundleActivator} 实现.
 *
 * @author Lam Tong
 */
public class ClientBundleActivator implements BundleActivator {

    private static final Logger logger = Logger.getLogger(ClientBundleActivator.class.getName());

    private ServiceReference<HelloService> serviceReference;

    @Override
    public void start(BundleContext context) {
        logger.log(Level.INFO, "Client Bundle start");
        this.serviceReference = context.getServiceReference(HelloService.class);
        if (this.serviceReference != null) {
            HelloService helloService = context.getService(this.serviceReference);
            logger.log(Level.INFO, "Get [HelloService] instance: " + helloService);
            String response = helloService.hello();
            logger.log(Level.INFO, "Invoke instance and response: " + response);
            response = helloService.hello(UUID.randomUUID().toString());
            logger.log(Level.INFO, "Invoke instance and response: " + response);
        } else {
            logger.log(Level.INFO, "[HelloService]'s implementation does not exists.");
        }
    }

    @Override
    public void stop(BundleContext context) {
        logger.log(Level.INFO, "Client Bundle stop");
        if (this.serviceReference != null) {
            context.ungetService(this.serviceReference);
        }
    }

}
